package com.ait.oss.service.impl;

import com.ait.oss.service.OssService;
import com.ait.oss.utils.ConstantPropertiesUtils;
import com.ait.oss.utils.InitObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private ConstantPropertiesUtils constantPropertiesUtils;


    /*
    *
    * 上传到oss
    *
    *
    *
    * 返回图片连接例如https://gui-lizhuang.oss-cn-zhangjiakou.aliyuncs.com/2021/06/10/12550476.jpeg
    *
    *
    * */
    @Override
    public String uploadFileAvatar(MultipartFile file) {

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
                String endpoint = constantPropertiesUtils.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
                String accessKeyId = constantPropertiesUtils.getAccessKeyId();
                String accessKeySecret = constantPropertiesUtils.getAccessKeySecret();
                String bucketName = constantPropertiesUtils.getBucketName();
        try {
            // 创建OSSClient实例。 参数是 你oss地址 密钥id 和 密钥
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //获取上传的输入流
            InputStream inputStream = file.getInputStream();

            String filename = file.getOriginalFilename();//获取原始文件名
            String suffix = filename.substring(filename.lastIndexOf("."));
            String name = UUID.randomUUID().toString().replaceAll("-","").substring(0,8)+suffix;

            //时间流
            String datapath = new DateTime().toString("yyyy/MM/dd");
            filename = datapath+"/"+name;
            // 调用oss方法实现上传 第一个参数是oss名称 第二个参数是文件名filename="2021/06/11/filename.jpg"第三个对象是你的文件
            ossClient.putObject(bucketName,filename,inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
            String Url = "https://"+bucketName+"."+endpoint+"/"+filename;
            return Url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }



    }

    /*  上传视频*/

    @Override
    public Map<String, Object> uploadFileVideo(MultipartFile file){
        String filename = file.getOriginalFilename();
        String title =  UUID.randomUUID().toString().replaceAll("-","").substring(0,8);//上传之后的文件名称
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //
        UploadStreamRequest request = new UploadStreamRequest(constantPropertiesUtils.getAccessKeyId(), constantPropertiesUtils.getAccessKeySecret(), title, filename,inputStream);


        //上传
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        String id;
        if (response.isSuccess()) {
            id= response.getVideoId();
        } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
            id= response.getVideoId();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("name",title);
        map.put("id",id);

        return map;
    }

    /*
    * 删除视频
    *
    * 删除成功返回true失败false
    *
    * */

    @Override
    public Boolean DeleteFileVideo(String id) {
        DefaultAcsClient client = InitObject.initVodClient(constantPropertiesUtils.getAccessKeyId(), constantPropertiesUtils.getAccessKeySecret());

        DeleteVideoRequest request = new DeleteVideoRequest();

        request.setVideoIds(id);

        try {
            client.getAcsResponse(request);
            return true;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }

    }

    /*
       * 排列删除视频
       *
       * 删除成功返回true失败false
       *
       * */
    @Override
    public Boolean DeleteBatchFileVideo(List videoList) {

        //这个是初始化对象
        DefaultAcsClient client = InitObject.initVodClient(constantPropertiesUtils.getAccessKeyId(), constantPropertiesUtils.getAccessKeySecret());

        DeleteVideoRequest request = new DeleteVideoRequest();


        request.setVideoIds(StringUtils.join(videoList.toArray(),","));

        try {
            client.getAcsResponse(request);
            return true;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }


    //
    @Override
    public String getplayAuths(String id) {
        try{
            //初始化对象
            DefaultAcsClient client = InitObject.initVodClient(constantPropertiesUtils.getAccessKeyId(), constantPropertiesUtils.getAccessKeySecret());

            //创建获取凭证request
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();

            //向request设置视频id
            request.setVideoId(id);

            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);

            return response.getPlayAuth();//返回密钥
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}

